package com.kfm.servlet.day04;

import com.kfm.servlet.day04.db.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;

@WebServlet("/uploadv2")
@MultipartConfig
public class UploadServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 进入到 uploadv2.html 页面
        req.getRequestDispatcher("/WEB-INF/pages/uploadv2.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 上传文件
        Part file = req.getPart("file");

        if (file != null) {
            // 获取文件名
            String fileName = file.getSubmittedFileName();
            // 获取文件的大小
            long fileSize = file.getSize();
            // 获取文件的类型
            String fileType = file.getContentType();

            // 获取文件的后缀名
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            // 防止文件名重复，使用 UUID 生成一个随机的文件名
            String name = UUID.randomUUID().toString().replace("-", "") + suffix;


            // 根据日期创建文件夹
            LocalDate now = LocalDate.now();
            String datePath = "" + now.getYear() + File.separator + now.getMonthValue() + File.separator + now.getDayOfMonth() ;
            File dir = new File(Constants.UPLOAD_BASE_PATH, datePath);
            if (!dir.exists()){
                dir.mkdirs();
            }


            String savePath = datePath + File.separator + name;

            // 存数据到数据库
            DBUtils dbUtils = new DBUtils(1);

            String sql = "insert into file (name, path, size, type, upload_time) values (?, ?, ?, ?, ?)";
            int update = dbUtils.update(sql, fileName, savePath, fileSize, fileType, LocalDateTime.now());

            if (update > 0) {
                System.out.println("保存成功");
                // 保存文件
                file.write(dir + File.separator + name);
//                req.getRequestDispatcher("filelist").forward(req, resp);
                resp.sendRedirect("filelist");
            } else {
                System.out.println("保存失败");
                resp.sendRedirect("uploadv2");
            }



        }
    }

    public static void main(String[] args) {
        String fileName = "12.2.3.jpg";
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(suffix);
    }
}


